package me.shan.data.structure;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述：栈，先进后出 数组实现
 *
 * @author liuchuang
 * @date 2021/7/6 11:02
 */
public class ArrayStack {

    /**
     * 栈中元素数量
     */
    private int size;

    public int getSize() {
        return size;
    }

    /**
     * 最大元素数量
     */
    private static final int MAX_SIZE = 100;

    /**
     * 数据数组
     */
    private final int[] elementData = new int[MAX_SIZE];

    public void push(int value) throws Exception {
        if (size == MAX_SIZE) {
            throw new Exception("栈已满，不允许push操作");
        }
        elementData[size] = value;
        size++;
    }

    public List<Integer> getElementList() {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            list.add(elementData[i]);
        }
        return list;
    }

    public int pop() throws Exception {
        if (size == 0) {
            throw new Exception("空栈，不允许pop操作");
        }
        int value = elementData[size - 1];
        size--;
        return value;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("ArrayStack{size=");
        stringBuilder.append(size);
        stringBuilder.append(", elementData=[");
        for (int i = 0; i < size; i++) {
            stringBuilder.append(elementData[i]);
            if (i != size - 1) {
                stringBuilder.append(",");
            }
        }
        stringBuilder.append("]}");
        return stringBuilder.toString();
    }

    public static void main(String[] args) throws Exception {
        ArrayStack stack = new ArrayStack();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        System.out.println(stack);
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        stack.push(5);
        System.out.println(stack);
    }

}
